﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using WebApplication1.Base;

namespace WebApplication1.Tools.CreateUI
{
    public class TableColumn
    {       
        public string TableName { get; set; }       
        public string TableComments { get; set; }       
        public string Name { get; set; }       
        public string Comments { get; set; }       
        public string Type { get; set; }
        public int Length { get; set; }       
        public bool IsNull { get; set; }       
        public bool IsPrimaryKey { get; set; }
        public bool IsIdentity { get; set; }
    }
    public class Table
    {
        public string Name { get; set; }
        public string Comments { get; set; }
        public string PrimaryName { get; set; }
        public List<TableColumn> Columns { get; set; }
    }


    public partial class Index : System.Web.UI.Page
    {
        //static List<Table> tableList = new List<CommonLib.Model.Table>();
        static List<TableColumn> columnList = new List<TableColumn>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                columnList = new List<TableColumn>();
                文件路径TextBox.Text = HttpContext.Current.Server.MapPath("/Tools/CreateUI/Code/");
                //tableList = new CommonLib.DbHelper.Table().DicTable.Select(ex => ex.Value).ToList();
                var list = DbSql.DB.Ado.SqlQuery<dynamic>(@"SELECT 
    t.TABLE_NAME AS 表名,
    t.TABLE_COMMENT AS 表说明,
    c.COLUMN_NAME AS 字段名,
    c.COLUMN_COMMENT AS 字段说明,
    CASE 
        WHEN c.COLUMN_KEY = 'PRI' THEN '是'
        ELSE '否'
    END AS IsPrimaryKey,
    CASE
        WHEN c.IS_NULLABLE = 'YES' THEN '是'
        ELSE '否'
    END AS 可空,
    c.CHARACTER_MAXIMUM_LENGTH AS 字段长度,
    c.COLUMN_TYPE AS 字段类型
FROM 
    information_schema.TABLES t
JOIN
    information_schema.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA
WHERE
    t.TABLE_SCHEMA = 'base' and t.TABLE_NAME='system_menu'
ORDER BY
    t.TABLE_NAME, c.ORDINAL_POSITION;");
                foreach (var item in list)
                {
                    columnList.Add(new TableColumn()
                    {
                        TableName = item.表名.ToString(),
                        TableComments = item.表说明.ToString(),
                        Name = item.字段名.ToString(),
                        Comments = item.字段说明.ToString(),
                        IsPrimaryKey = false,
                        IsNull = ((!(item.可空.ToString() == "0")) ? true : false),
                        Length = Convert.ToInt32(item.字段长度),
                        Type = item.字段类型.ToString()

                    });
                }

                DataBind_tb();
                DataBind_tbInfo();

                DataBind_tbInfo();
            }
        }



        #region 绑定数据

        /// <summary>
        /// 表字段结构
        /// </summary>
        private void DataBind_tb()
        {
            Repeater1.DataSource = columnList;
            Repeater1.DataBind();

            文件名TextBox.Text = Request["name"].ToString();
        }

        /// <summary>
        /// 表注释信息
        /// </summary>
        private void DataBind_tbInfo()
        {
            文件名TextBox.Text = columnList.FirstOrDefault().TableName;
            标题头TextBox.Text = columnList.FirstOrDefault().Comments;
        }
        #endregion 绑定数据

        #region 效验文件夹  生成代码文件

        protected void 效验Button_Click(object sender, EventArgs e)
        {
            string SavedFolder = 文件路径TextBox.Text.Trim();
            if (SavedFolder.Substring(SavedFolder.Length - 1, 1) != "\\")
            {
                SavedFolder += "\\";
            }
            SavedFolder += Request["name"].ToString() + "\\";
            if (Directory.Exists(SavedFolder))
            {
                信息Literal.Text = "<font color='red'>程序存在，请慎重生成！</font>";
            }
            else
            {
                信息Literal.Text = "<font color='green'>程序不存在，可以放心生成！</font>";
            }
        }

        protected void 生成Button_Click(object sender, EventArgs e)
        {
            if (文件路径TextBox.Text.Trim() != "")
            {
                string tbName = 文件名TextBox.Text.Trim();
                string tbNotes = 标题头TextBox.Text.Trim();

                Create("Index.txt", "Index.aspx", tbName, tbNotes);
                Create("edit.txt", "edit.aspx", tbName, tbNotes);
                Create("details.txt", "details.aspx", tbName, tbNotes);

                Create("controller.txt", tbName + "Controller.cs", tbName, tbNotes, "Controller");

                Create("V1/Request.txt", "Request.cs", tbName, tbNotes, "EntityV1/" + tbName);
                Create("V1/Response.txt", "Response.cs", tbName, tbNotes, "EntityV1/" + tbName);
            }
        }

        /// <summary>
        /// 生成首页代码
        /// </summary>
        /// <param name="tbName">表名称</param>
        /// <param name="tbNotes">表注释</param>
        private void Create(string template, string writeName, string tbName, string tbNotes, string config = "")
        {
            string SavedFolder = 文件路径TextBox.Text.Trim();

            if (SavedFolder.Substring(SavedFolder.Length - 1, 1) != "\\")
            {
                SavedFolder += "\\";
            }
            if (config != "")//服务
            {
                SavedFolder += config + "\\";
            }
            else
            {
                SavedFolder += Request["name"].ToString() + "\\";
            }
            if (!Directory.Exists(SavedFolder))
            {
                Directory.CreateDirectory(SavedFolder);
            }

            string writePath = SavedFolder + writeName;
            string str = txt_read("/Tools/CreateUI/Template/" + template);

            str = str.Replace("$表名$", tbName);
            var item = tbName.Split('_');
            if (item.Length > 1)
            {
                str = str.Replace("$表名1$", item[1]);
            }
            else
            {
                str = str.Replace("$表名1$", tbName);
            }
            str = str.Replace("$表名注释$", tbNotes);

            str = str.Replace("$列表页布局$", Index_html(tbName));
            str = str.Replace("$编辑页面布局$", Edit_html(tbName));
            str = str.Replace("$详细页面布局$", details_html(tbName));

            str = str.Replace("$绑定数据脚本$", Edit_DataBindjs(tbName));
            str = str.Replace("$编辑赋值脚本$", Edit_js(tbName));
            str = str.Replace("$详细页绑定数据脚本$", details_DataBindjs(tbName));

            str = str.Replace("$大E实体$", 大E实体(tbName));

            //str = str.Replace("$小E赋值给大E$", ExtendUpdate1(tbName));
            //str = str.Replace("$大E赋值给小E$", ExtendUpdate2(tbName));

            txt_write(writePath, str);

            信息Literal.Text = "<font color='red'>页面生成成功！</font>";
        }



        #endregion 效验文件夹  生成代码文件

        #region 返回html布局代码块

        /// <summary>
        /// 首页布局代码
        /// </summary>
        /// <returns></returns>
        private string Index_html(string tbName)
        {
            var zhCol = new List<dynamic> { "isdel", "adduserid", "lastuserid" };

            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                var width = item.Name == "ID" ? "75" : "150";

                if (item.Type == "datetime")
                {
                    str += string.Format("<th data-options=\"field: '{0}',width: {2},formatter:function(val,rec){{ return $.DateFormat(val, 'yyyy-MM-dd HH:mm:ss'); }}\">{1}</th>\r\n", item.Name, item.Comments, width);
                }
                else if (zhCol.Contains(item.Name))
                {
                    str += string.Format("<th data-options=\"field: '{0}_Name',width: {2}\">{1}</th>\r\n", item.Name, item.Comments, width);
                }
                else
                {
                    str += string.Format("<th data-options=\"field: '{0}',width: {2}\">{1}</th>\r\n", item.Name, item.Comments, width);
                }
            }
            return str;
        }
        /// <summary>
        /// 编辑页布局
        /// </summary>
        /// <returns></returns>
        private string Edit_html(string tbName)
        {
            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                var control = "<input id='{0}' name='{0}' type='text' class='validate[required]' data-prompt-position='bottomRight' />";
                var tdid = "";
                if (item.IsPrimaryKey)
                {
                    control = "<span id='{0}' name='{0}'>自动</span>";
                }
                else if (item.Name == "ID" || item.Name == "IsDelete" || item.Name == "AddTime" || item.Name == "LastTime" || item.Name == "AddUserID" || item.Name == "LastUserId")
                {
                    control = "自动";
                    tdid = " id='" + item.Name + "'";
                }
                else if (item.Type == "datetime")
                {
                    control = "<input id='{0}' name='{0}' type='text'  class='Wdate validate[required]' onclick='WdatePicker()' data-prompt-position='bottomRight' />";
                }

                //if (item.Name != "ID" && item.Name != "IsDelete" && item.Name != "AddUserID" && item.Name != "LastTime" && item.Name != "LastUserId")
                {
                    str += string.Format(string.Format(@"<li>
                                        <em class='l_name'>{1}：</em>
                                        <div{2}  class='r_con1'>" + control + "</div></li>", item.Name, item.Comments, tdid));
                }
            }
            return str;
        }
        /// <summary>
        /// 详细页布局
        /// </summary>
        /// <returns></returns>
        private string details_html(string tbName)
        {
            var zhCol = new List<dynamic> { "IsDelete", "AddUserID", "LastUserId" };
            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                if (zhCol.Contains(item.Name))
                {
                }
                str += string.Format(string.Format(@"<li>
                                        <em class='l_name'>{1}：</em>
                                        <div class='r_con' id='{0}'></div></li>", item.Name, item.Comments));
            }
            return str;
        }
        /// <summary>
        /// 编辑脚本
        /// </summary>
        /// <returns></returns>
        private string Edit_js(string tbName)
        {
            var NoCol = new List<dynamic> { "IsDelete", "AddUserID", "LastUserId", "LastTime", "AddTime" };

            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                if (NoCol.Contains(item.Name))
                {

                }
                else if (item.Type == "datetime")
                {
                    str += string.Format(string.Format("obj.{0} = $.JsonDateFy($.GetValue(\"{0}\") == \"自动\" ? $.GetDateTime() : $.GetValue(\"{0}\"));\r\n", item.Name));
                }
                else if (item.IsPrimaryKey == false)
                {
                    str += string.Format(string.Format("obj.{0} = $.GetValue(\"{0}\");\r\n", item.Name));
                }
            }
            return str;
        }
        /// <summary>
        /// 编辑绑定数据脚本
        /// </summary>
        /// <returns></returns>
        private string Edit_DataBindjs(string tbName)
        {
            var zhCol = new List<dynamic> { "IsDelete", "AddUserID", "LastUserId" };
            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                if (item.Type == "datetime")
                {
                    str += string.Format(string.Format("$.SetValue(\"{0}\", $.DateFormat(obj.{0}, 'yyyy-MM-dd HH:mm:ss'));\r\n", item.Name));
                }
                else if (zhCol.Contains(item.Name))
                {
                    str += string.Format(string.Format("$.SetValue(\"{0}\", obj.{0}_Name);\r\n", item.Name));
                }
                else
                {
                    str += string.Format(string.Format("$.SetValue(\"{0}\", obj.{0});\r\n", item.Name));
                }
            }
            return str;
        }

        /// <summary>
        /// 详细页绑定数据脚本
        /// </summary>
        /// <returns></returns>
        private string details_DataBindjs(string tbName)
        {
            var zhCol = new List<dynamic> { "IsDelete", "AddUserID", "LastUserId" };
            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                if (item.Type == "datetime")
                {
                    str += string.Format(string.Format("$.SetValue(\"{0}\", $.DateFormat(obj.{0}, 'yyyy-MM-dd HH:mm:ss'));\r\n", item.Name));
                }
                else if (zhCol.Contains(item.Name))
                {
                    str += string.Format(string.Format("$.SetValue(\"{0}\", obj.{0}_Name);\r\n", item.Name));
                }
                else
                {
                    str += string.Format(string.Format("$.SetValue(\"{0}\", obj.{0});\r\n", item.Name));
                }
            }
            return str;
        }



        private string ExtendUpdate1(string tbName)
        {
            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                if (item.Name != "ID" && item.Name != "AddUserID" && item.Name != "IsDelete" && item.Name != "AddTime" && item.Name != "OrgLevels" && item.Name != "CityLevels")
                {
                    str += string.Format("{0} = baseClass.{0};\r\n", item.Name);
                }
            }
            return str;
        }
        private string ExtendUpdate2(string tbName)
        {
            var str = "";
            var list = columnList;
            foreach (var item in list)
            {
                if (item.Name != "ID" && item.Name != "AddUserID" && item.Name != "IsDelete" && item.Name != "AddTime" && item.Name != "OrgLevels" && item.Name != "CityLevels")
                {
                    str += string.Format("baseClass.{0} = this.{0};;\r\n", item.Name);
                }
            }
            return str;
        }

        #endregion 返回html布局代码块

        #region 大E实体

        private string 大E实体(string tbName)
        {
            var Columns = columnList;
            var AddUpdate = "";
            foreach (var item in Columns)
            {
                if (item.Name != "ID" && item.Name != "AddTime" && item.Name != "IsDelete" && item.Name != "OrgLevels" && item.Name != "CityLevels" && item.Name != "AddUserID" && item.Name != "LastUserId" && item.Name != "LastTime")
                {
                    AddUpdate += string.Format(@" /// <summary>
        /// {0}
        /// </summary>
       
        public {1} {2} {{ get; set; }}" + "\r\n\r\n", item.Comments, GetType(item.Type), item.Name);

                }
            }
            return AddUpdate;
        }

        public string GetType(string name)
        {
            var type = "string";
            switch (name)
            {
                case "uniqueidentifier":
                    {
                        type = "int?";
                        break;
                    }
                case "int":
                    {
                        type = "Nullable<int>";
                        break;
                    }
                case "bit":
                    {
                        type = "Nullable<bool>";
                        break;
                    }
                case "datetime":
                    {
                        type = "Nullable<System.DateTime>";
                        break;
                    }
                case "decimal":
                    {
                        type = "Nullable<decimal>";
                        break;
                    }
            }
            return type;
        }
        #endregion

        #region 文件读写

        /// <summary>
        /// 文件写入方法
        /// </summary>
        /// <param name="path">文件路径:相对路径</param>
        /// <param name="str">写入内容</param>
        /// <param name="encoding">编码格式</param>
        public static void txt_write(string path, string str, bool append = false, string encoding = "utf-8")
        {
            System.Text.Encoding code = System.Text.Encoding.GetEncoding(encoding);
            System.IO.StreamWriter sw = null;
            try
            {
                sw = new System.IO.StreamWriter(path, append, code);
                sw.Write(str);
                sw.Flush();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
        }

        /// <summary>
        /// 文件读取方法
        /// </summary>
        /// <param name="path">文件路径:相对路径</param>
        /// <param name="encoding">编码格式</param>
        public static string txt_read(string path, string encoding = "utf-8")
        {
            //源码是替换掉模板中的特征字符            
            string Path = System.Web.HttpContext.Current.Server.MapPath(path);
            Encoding code = Encoding.GetEncoding(encoding);
            System.IO.StreamReader Sr = null;

            string str = "";

            //读取
            try
            {
                Sr = new StreamReader(Path, code);
                str = Sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Sr.Close();
            }
            return str;
        }

        #endregion 文件读写
    }
}